package com.zrwl.poscloud.commons.utils;

import cn.hutool.core.util.HexUtil;
import org.junit.Test;

/**
 * @author 刘思童
 * @create 2021-06-22 18:37
 **/
public class CRCUtil {
    @Test
    public void test() {
        String scrc = "0001F0001D00062099989B020000271000010000000000010027100002220101016d";
        validateByte(scrc);
    }

    public static String getCrc(String str) {
        return getCrc(HexUtil.decodeHex(str.toCharArray())).toUpperCase();
    }

    public static boolean validateByte(String str) {
//		System.out.println("开始校验："+str);
        //测试期间不校验
        if(true)return true;
        if (str == null || "".equals(str)) return false;
        int start = 0;
        if (str.startsWith("FE")||str.startsWith("fe")) {//有带帧头
            //原数据含帧头+CRC。
            start = 1;
        } else {
            start = 0;
        }
        try {
            String crc = str.substring(str.length() - 4);
            String scrc = str.substring(start * 2, str.length() - start * 2 - 2);
//			System.out.println("校验str："+scrc);
            String rcrc = getCrc(HexUtil.decodeHex(scrc.toCharArray()));
//			System.out.println("正确的crc："+rcrc);
//			System.out.println("实际的crc："+crc);
            return rcrc.equals(crc.toLowerCase());
        } catch (Exception e) {
            return false;
        }

    }

    public static String getCrc(byte[] data) {
        byte[] buf = new byte[data.length];// 存储需要产生校验码的数据
        for (int i = 0; i < data.length; i++) {
            buf[i] = data[i];
        }
        int len = buf.length;
        int crc = 0xFFFF;
        for (int pos = 0; pos < len; pos++) {
            if (buf[pos] < 0) {
                crc ^= (int) buf[pos] + 256; // XOR byte into least sig. byte of
                // crc
            } else {
                crc ^= (int) buf[pos]; // XOR byte into least sig. byte of crc
            }
            for (int i = 8; i != 0; i--) { // Loop over each bit
                if ((crc & 0x0001) != 0) { // If the LSB is set
                    crc >>= 1; // Shift right and XOR 0xA001
                    crc ^= 0xA001;
                } else
                    // Else LSB is not set
                    crc >>= 1; // Just shift right
            }
        }
        String c = Integer.toHexString(crc);
        if (c.length() == 4) {
            c = c.substring(2, 4) + c.substring(0, 2);
        } else if (c.length() == 3) {
            c = "0" + c;
            c = c.substring(2, 4) + c.substring(0, 2);
        } else if (c.length() == 2) {
            c = c + "00";// + c.substring(0, 1) + "0" + c.substring(1, 2);
        } else if (c.length() == 1) {
            c = "0" + c + "00";// + c.substring(0, 1) + "0" + c.substring(1, 2);
        }
        return c;
    }

}
